package com.aaa.util;

import com.aaa.util.PictureUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Description: 图片上传身份证正反面、上传照片
 * @Author: 陈阳
 * @CreateDate: 2018/12/27$ 9:44$
 */
@CrossOrigin
@Controller
@RequestMapping("/IDCardUploadImg")
public class IDCardUploadImg {

    @RequestMapping("/uploadIDCard")
    public void uploadIDCard(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String imageBase64 = req.getParameter("imageBase64");
        //将base64的图片编码存储至服务器，并将路径修改至数据库
        //前台是以png的格式存储的
        String type = "data:image/png;base64,";
        imageBase64 = imageBase64.substring(type.length());
        String realPath = "head_photo" + File.separator + "123" + ".png";
        JSONObject json = new JSONObject();
        try {
            File file = IDCardUploadImg.uploadFileByBase64(realPath, imageBase64);
            String s = PictureUtil.getPicture(file);
            json.put("result", "success");
            json.put("message", s);
        } catch (Exception e) {
            json.put("result", "error");
            json.put("message", "上传图片失败!");
            e.printStackTrace();
        }
        //将参数输出至浏览器
        PrintWriter out = resp.getWriter();
        out.write(json.toJSONString());
        out.flush();
        out.close();
    }

    public static File uploadFileByBase64(String destRealPath, String imageBase64) throws Exception {
        OutputStream out = null;
        try {
            byte bytes[] = Base64.decodeFast(imageBase64);
            //这里是我的获取图片文件服务器的路径，可以是随便一个地址，如d:\\temp\\之类的
            String imageServer = "D:\\";
            String destFilePath = imageServer + File.separator + destRealPath;
            File destFile = new File(destFilePath);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            for (int i = 0, lens = bytes.length; i < lens; i++) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            out = new FileOutputStream(destFile);
            out.write(bytes);
            return destFile;
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
